package com.setup.trac.controller;

import java.math.BigDecimal;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractWizardFormController;

import com.setup.trac.controller.validator.CreateUserValidator;
import com.setup.trac.pojo.Profilo;
import com.setup.trac.pojo.Progetti;
import com.setup.trac.pojo.Societa;
import com.setup.trac.pojo.Utenti;
import com.setup.trac.pojo.condition.FindSocietaById;
import com.setup.trac.pojo.condition.FinderProfiloById;
import com.setup.trac.pojo.condition.FinderProgettiByIds;
import com.setup.trac.service.AdminService;
import com.setup.trac.service.MailSenderService;
import com.setup.trac.service.SearchService;
import com.setup.trac.util.Browser;
import com.setup.trac.util.Container;
import com.setup.trac.util.SQLCondition;
import com.setup.trac.util.TracSetupUtil;

public class CreateUserController extends AbstractWizardFormController {

	private AdminService adminService;
	private SearchService searchService;
	private Browser browser;
	private XWizardController[] wizardControllers;
	private MailSenderService mailSenderService;
	private Properties properties;

	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		try {
			return createUser(request, response, command, errors);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	protected ModelAndView createUser(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {

		Utenti user = (Utenti) command;
		SQLCondition sqlCondition = new FinderProfiloById(
				request.getParameter("idProfilo"));
		Profilo profilo = getSearchService().find(new Profilo[0], sqlCondition,
				Profilo.class)[0];
		user.setProfilo(profilo);
		String[] idProgettis = request
				.getParameterValues("progettiSelezionati");

		sqlCondition = new FinderProgettiByIds(idProgettis);

		Progetti[] progetto = getSearchService().find(new Progetti[0],
				sqlCondition, Progetti.class);
		for (int i = 0; i < progetto.length; i++) {
			Progetti p = progetto[i];
			user.getProgettis().add(p);
			p.getUtentis().add(user);
		}
		user = getAdminService().insertUtente(user);
		return null;// ,errors.getModel());
	}

	// protected ModelAndView showForm(HttpServletRequest request,
	// HttpServletResponse response, BindException errors, Map controlModel)
	// throws Exception {
	// request.getSession(false).removeAttribute("progettiSelezionati");
	// ModelAndView modelAndView = super.showForm(request, response, errors,
	// controlModel);
	// modelAndView.setViewName(getFormView());
	// return modelAndView;
	// }

	public AdminService getAdminService() {
		return adminService;
	}

	public void setAdminService(AdminService adminService) {
		this.adminService = adminService;
	}

	@Override
	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		Utenti command = (Utenti) request.getSession(false).getAttribute(
				"utente");
		if (command == null) {
			command = new Utenti();
		}
		return command;
	}

	// @Override
	// protected Map referenceData(HttpServletRequest request, Object command,
	// Errors errors) throws Exception {
	// Map<String, Object> model = new HashMap<String, Object>();
	// String action = request.getParameter("op");
	// String commandName = getCommandName();
	// model.put(commandName, command);
	// return model;
	// }

	public SearchService getSearchService() {
		return searchService;
	}

	public void setSearchService(SearchService searchService) {
		this.searchService = searchService;
	}

	public Browser getBrowser() {
		return browser;
	}

	public void setBrowser(Browser browser) {
		this.browser = browser;
	}

	@Override
	protected ModelAndView processFinish(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		Utenti user = (Utenti) command;
		String[] idProgettis = request
				.getParameterValues("progettiSelezionati");
		String idCliente = request.getParameter("idCliente");
		SQLCondition findSocietaById=new FindSocietaById(idCliente);
		Societa societa = getSearchService().find(new Societa[0], findSocietaById, Societa.class)[0];
		user.setSocieta(societa);
		SQLCondition sqlCondition = new FinderProfiloById((String) request
				.getSession(false).getAttribute("idProfilo"));
		Profilo profilo = getSearchService().find(new Profilo[0], sqlCondition,
				Profilo.class)[0];
		user.setProfilo(profilo);
		sqlCondition = new FinderProgettiByIds(idProgettis);
		Progetti[] progetto = getSearchService().find(new Progetti[0],
				sqlCondition, Progetti.class);
		for (int i = 0; i < progetto.length; i++) {
			Progetti p = progetto[i];
			user.getProgettis().add(p);
			p.getUtentis().add(user);
		}
		if(isUppercaseUserName()){
			user.setUsername(user.getUsername().toUpperCase());
		}
		if(isUppercasePassword()){
			user.setPassword(user.getPassword().toUpperCase());
		}
		String decPassword = user.getPassword();
		user.setAbilitato(true);
		user.setErroreAccesso(new BigDecimal(0));
		user = getAdminService().insertUtente(user);
		user.setPassword(decPassword);
		String url = "http://www.setup.torino.it/tracsetup/login.do";
		mailSenderService.sendMessage(user,url);
		return new ModelAndView("adminConsole");// ,errors.getModel());
	}


	@Override
	protected void validatePage(Object command, Errors errors, int page) {
		// TODO Auto-generated method stub
		super.validatePage(command, errors, page);
	}

	@Override
	protected void onBindAndValidate(HttpServletRequest request,
			Object command, BindException errors, int page) throws Exception {
		CreateUserValidator validator = (CreateUserValidator) getValidator();
		validator.validateRequestParams(request, command, errors);
		if (request.getParameter("idProfilo") != null) {
			request.getSession(false).setAttribute("idProfilo",
					request.getParameter("idProfilo"));
		}
		if (page < getWizardControllers().length) {
			XWizardController action = getWizardControllers()[page];
			action.execute(request, null, command, errors);
		}

		// do nothing!
		// super.onBindAndValidate(request, command, errors, page);
	}

	public XWizardController[] getWizardControllers() {
		return wizardControllers;
	}

	public void setWizardControllers(XWizardController[] wizardController) {
		this.wizardControllers = wizardController;
	}

	@Override
	protected void postProcessPage(HttpServletRequest request, Object command,
			Errors errors, int page) throws Exception {
		super.postProcessPage(request, command, errors, page);
	}

	@Override
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// memorizzo nel ThreadLocal l'oggetto request per fare controlli sui
		// progetti selezionati
		ModelAndView mav = super.handleRequest(request, response);
		Container.set(request);
		return mav;
	}

	public MailSenderService getMailSenderService() {
		return mailSenderService;
	}

	public void setMailSenderService(MailSenderService mailSenderService) {
		this.mailSenderService = mailSenderService;
	}

	@Override
	protected void onBind(HttpServletRequest request, Object command,
			BindException errors) throws Exception {
		// TODO Auto-generated method stub
		super.onBind(request, command, errors);
	}

	public boolean isUppercaseUserName() {
		return getProperties().getProperty("uppercaseUserName").equalsIgnoreCase("true");
	}


	public boolean isUppercasePassword() {
		return getProperties().getProperty("uppercasePassword").equalsIgnoreCase("true");
	}


	public Properties getProperties() {
		return properties;
	}

	public void setProperties(Properties properties) {
		this.properties = properties;
	}

}
